<?php
declare(strict_types=1);

namespace App\Service;

use App\Utils\CustomUtils;
use Hyperf\Di\Annotation\Inject;
use App\Model\Dao\EmailSendLogDao;
use App\Model\Dao\EmailTemplateDao;
use App\Exception\XZXValidationException;
use App\Constants\XZXResponseCode;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Coroutine;
use Swlib\SaberGM;
use Hyperf\Utils\Codec\Json;
use App\Utils\RedisUtils;



class EmailService
{
    /**
     * @Inject()
     * @var EmailSendLogDao
     */
    private $EmailSendLogDao;

    /**
     * @Inject()
     * @var EmailTemplateDao
     */
    private $EmailTemplateDao;

    const SEND_MAIL     = "/api/mail/send";

    //
    // {"type":1,"regEmail":"ee@xxx.com"}
    // {"type":2,"regEmail":"ee@xxx.com"}
    // {"type":3,"toEmail":"fasd@sd.com"}
    //
    public function send($param){
        CustomUtils::xzxDebug($param);
        $data = array();
        switch($param['type']){
            case 1:
                //商户注册发送的邮件验证码
                if(!isset($param['regEmail'])){
                    //throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
                    CustomUtils::xzxDebug("没有regEmail，直接丢弃。");
                    return false;
                }
                $data['toEmail'] = $param['regEmail'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 1
                // );            
                break;
            case 2:
                // $quereParam = array(
                //     'type' => 2
                // );
                $data['toEmail'] = $param['regEmail'];
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }
                if(!isset($param['mchNo'])){                    
                    CustomUtils::xzxDebug("没有mchNo，直接丢弃。");
                    return false;
                }    
                if(!isset($param['tradeNo'])){                    
                    CustomUtils::xzxDebug("没有tradeNo，直接丢弃。");
                    return false;
                }                     
                $data['toEmail'] = $param['email'];                        
                // $quereParam = array(
                //     'type' => $param['type']
                // );
                break; 
            case 7:
            case 8:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }
                if(!isset($param['mchNo'])){                    
                    CustomUtils::xzxDebug("没有mchNo，直接丢弃。");
                    return false;
                }    
                if(!isset($param['transNo'])){                    
                    CustomUtils::xzxDebug("没有transNo，直接丢弃。");
                    return false;
                }                     
                $data['toEmail'] = $param['email'];                        
                // $quereParam = array(
                //     'type' => $param['type']
                // );
                break;    
            case 9:
            case 10:
            case 11:
            case 12:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }
                if(!isset($param['mchNo'])){                    
                    CustomUtils::xzxDebug("没有mchNo，直接丢弃。");
                    return false;
                }    
                                   
                $data['toEmail'] = $param['email'];                        
                // $quereParam = array(
                //     'type' => $param['type']
                // );
                break;           
            case 13:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }
                if(!isset($param['password'])){                    
                    CustomUtils::xzxDebug("没有password，直接丢弃。");
                    return false;
                }
                if(!isset($param['username'])){                    
                    CustomUtils::xzxDebug("没有username，直接丢弃。");
                    return false;
                }
                if(!isset($param['googleAuthSecret'])){                    
                    CustomUtils::xzxDebug("没有googleAuthSecret，直接丢弃。");
                    return false;
                }
                $data['toEmail'] = $param['email'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 13
                // );
                
                break; 
            case 14:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }
                if(!isset($param['hashCode'])){                    
                    CustomUtils::xzxDebug("没有hashCode，直接丢弃。");
                    return false;
                }
                $data['toEmail'] = $param['email'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 14
                // );
                
                break;  
            case 15:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }                
                $data['toEmail'] = $param['email'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 15
                // );
                
                break;                   
            case 16:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }                
                $data['toEmail'] = $param['email'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 16
                // );
                
                break; 
            case 17:
            case 18:
            case 19:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }                
                $data['toEmail'] = $param['email'];
                // //取邮件模板
                // $quereParam = array(
                //     'type' => 17
                // );
            case 20:
                if(!isset($param['email'])){                    
                    CustomUtils::xzxDebug("没有Email，直接丢弃。");
                    return false;
                }  
                if(!isset($param['googleAuthSecret'])){                    
                    CustomUtils::xzxDebug("没有googleAuthSecret，直接丢弃。");
                    return false;
                }                               
                $data['toEmail'] = $param['email'];                
                break;                      
            default:

        }
        $quereParam = array(
            'type' => $param['type']
        );
        $templateInfo = $this->EmailTemplateDao->getWhere($quereParam);
        if(!$templateInfo){
            CustomUtils::xzxDebug("没有对应的邮件模板，直接丢弃。");
            return false;
        }
        $data['subject'] = $templateInfo['subject'];
        $data['mailBody'] = $this->formatMailBody($param,$templateInfo);

        if(config("isDev")){
            $data['toEmail'] = env('TO_EMAIL');
        }
        $mailSendData = array(
            'to' => $data['toEmail'],
            'subject' => $data['subject'],
            'body' => $data['mailBody'],
        );
        $ret = $this->_sendEmail($mailSendData);
        CustomUtils::xzxDebug($ret);
        $data['status'] = 1;
        $data['createTime'] = time();
        $data['type'] = $param['type'];
        if(!$ret)
        {
            $data['status'] = 0;
        }
        //写db
        $data['id'] = CustomUtils::createUUID();
        $this->EmailSendLogDao->insert($data);
        return true;        
    }

    private function _sendEmail($mailSendData)
    {
        $api = env('MESSAGE_URL').self::SEND_MAIL;
        CustomUtils::xzxDebug($api);
        $mailSendData = is_array($mailSendData) ? json::encode($mailSendData) : $mailSendData;
        $response = "";
        try {
            $response = SaberGM::post($api, $mailSendData, [
                'content-type' => 'application/json',
                'timeout' => 60,
            ])->getBody()->getContents();
        } catch (\Exception $e) {
            CustomUtils::xzxDebug($e);
            $response = false;
        }

        // $result = SaberGM::post($api, $params, ['timeout' => self::TIME_OUT])->getBody()->getContents();
        
        return $response;
        // return $this->_httpRequest($api,$mailSendData);
    }

    public function addMq($param) {

        RedisUtils::redisResource()->rPush("EmailList", serialize($param));
    }

    private function formatMailBody($param,$templateInfo){
        $mailbody = '';
        switch($param['type']){
            case 1:
            case 2:
                $mailbody = str_replace('${code}',$param['code'],$templateInfo['mailBody']);
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                $mailbody = str_replace('${mchNo}',$param['mchNo'],$templateInfo['mailBody']);
                $mailbody = str_replace('${tradeNo}',$param['tradeNo'],$mailbody);
                break; 
            case 7:
            case 8:
                $mailbody = str_replace('${mchNo}',$param['mchNo'],$templateInfo['mailBody']);
                $mailbody = str_replace('${transNo}',$param['transNo'],$mailbody);
                break;     
            case 9:
            case 10:
            case 11:
            case 12:
                $mailbody = str_replace('${mchNo}',$param['mchNo'],$templateInfo['mailBody']);
                // $mailbody = str_replace('${transNo}',$param['transNo'],$mailbody);
                break;                                            
            case 13:
                $mailbody = str_replace('${username}',$param['username'],$templateInfo['mailBody']);
                $mailbody = str_replace('${password}',$param['password'],$mailbody);
                $mailbody = str_replace('${email}',$param['email'],$mailbody);
                $mailbody = str_replace('${googleAuthSecret}',$param['googleAuthSecret'],$mailbody);
                break;
            case 14:
                $mailbody = str_replace('${hashCode}',$param['hashCode'],$templateInfo['mailBody']);
                break;
            case 15:
                $mailbody = str_replace('${tradeNo}',$param['tradeNo'],$templateInfo['mailBody']);
                break;  
            case 16:
                $mailbody = str_replace('${mchNo}',$param['mchNo'],$templateInfo['mailBody']);
                break;     
            case 17:
            case 18:
            case 19:
                $mailbody = str_replace('${mchNo}',$param['mchNo'],$templateInfo['mailBody']);
                break; 
            case 20:
                $mailbody = str_replace('${googleAuthSecret}',$param['googleAuthSecret'],$templateInfo['mailBody']);
                break;                                                             
            default:
        }
        return $mailbody;   
    }
    
}